﻿/*
* 创建者：LIYINFAI
* 创建时间：2023/10/31 15:40:53
* 描述：FileHelper
* --------------------------------------
* 修改说明：
* --------------------------------------
*/
using System;
using System.IO;
using System.Runtime.InteropServices;

namespace CommonLibrary
{
    /// <summary>
    /// 判断文件状态，-1不存在，0存在未打开，1文件被打开
    /// </summary>
    public class FileHelper
    {
        [DllImport("kernel32.dll")]
        private static extern IntPtr _lopen(string lpPathName, int iPeadWrite);
        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(IntPtr hObject);
        private const int OF_READWRITE = 2;
        private const int OF_SHARE_DENY_NONE = 0X40;
        private static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
        /// <summary>
        /// 判断文件是否打开
        /// </summary>
        /// <param name="fileFullName"></param>
        /// <returns></returns>
        public static int FileIsOpen(string fileFullName)
        {
            if (!File.Exists(fileFullName))
            {
                return -1;
            }
            IntPtr handle = _lopen(fileFullName, OF_READWRITE | OF_SHARE_DENY_NONE);
            if (handle == HFILE_ERROR)
            {
                return 1;
            }
            CloseHandle(handle);
            return 0;
        }
    }
}